package com.shelpe.service.simbaproxy.mock;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ResponseExceptionFilter extends ZuulFilter{

	private ObjectMapper objectMapper;
	
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		String in = context.getResponseBody();
		try {
			JsonNode node = this.objectMapper.reader().readTree(in);
			if(log.isDebugEnabled()){
				log.debug("json node: {}", node.toString());
			}
			
			if(node != null && node.has("error_response")){
				log.debug("set error status as taobao return error response");
				context.setResponseStatusCode(500);
			}
		} catch (JsonProcessingException e) {
			log.error("JsonProcessingException", e);
		} catch (IOException e) {
			log.error("IOException", e);
		}
		return null;
	}

	@Override
	public String filterType() {
		return "post";
	}

	@Override
	public int filterOrder() {
		return -1;
	}

	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

}
